package leetCode.firstWeek;

public class Code_8 {
  public int myAtoi(String str) {
    if (str.length() == 0 | (str.length() == 1 && str.equals("-"))) {
      return 0;
    }

    int start = 0, end, isMinus = 0;
    while (start < str.length() - 1 && (str.charAt(start) == ' ')) {
      start++;
    }
    if (str.charAt(start) == '+' | str.charAt(start) == '-') {
      if (str.charAt(start) == '-') {
        isMinus = 1;
      }
      start++;
    }
    end = start;
    while (end < str.length() && isNum(str.charAt(end))) {
      end++;
    }
    if (start == end) {
      return 0;
    }
    String resStr = str.substring(start, end);
    int resFinal;
    try {
      resFinal = Integer.parseInt(resStr);
    } catch (NumberFormatException e) {
      if (isMinus == 1 && resStr.length() >= 10) {
        return Integer.MIN_VALUE;
      } else if (isMinus == 0 && resStr.length() >= 10) {
        return Integer.MAX_VALUE;
      } else {
        return 0;
      }
    }
    return isMinus == 0 ? resFinal : -resFinal;
  }

  public static boolean isNum(Character chara) {
    if (chara >= 48 && chara <= 57) {
      return true;
    }
    return false;
  }
}
